<?php

namespace App\Http\Controllers\MiniAPP;

use App\Enums\MiniAPP\DuelStatus;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\MiniAPP\DuelRequest;
use App\Http\Resources\CRM\MiniAPP\DuelLevelResource;
use App\Http\Resources\CRM\MiniAPP\DuelTypeResource;
use App\Http\Resources\MiniAPP\DuelResource;
use App\Models\Duel;
use App\Models\DuelLevel;
use App\Models\DuelType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DuelController extends Controller
{
    public function getDuelTypeList()
    {
        $types = DuelType::latest()->get();

        return DuelTypeResource::collection($types);
    }

    public function getDuelLevelList()
    {
        $levels = DuelLevel::latest()->get();

        return DuelLevelResource::collection($levels);
    }

    public function create(DuelRequest $request)
    {
        $duel = Duel::create($request->only([
            'member_wechat',
            'start_at',
            'fake_table_type_id',
            'duel_type_id',
            'duel_level_id',
            'remark',
            'store_id',
        ]) + ['member_id' => Auth::id(), 'status' => DuelStatus::Pending]);

        return new DuelResource($duel);
    }

    public function getCanSignDuelList()
    {
        $duels = Duel::where('start_at', '>', now())
            ->where('member_id', '!=', Auth::id())
            ->where('status', DuelStatus::Pending)
            ->with([
                'member', 'opponent',
                'tableType', 'duelType', 'duelLevel', 'store',
            ])
            ->latest()
            ->paginate();

        return DuelResource::collection($duels);
    }

    public function getMineDuelList(Request $request)
    {
        $duels = Duel::where('member_id', Auth::id())
            ->with([
                'member', 'opponent',
                'tableType', 'duelType', 'duelLevel', 'store',
            ])
            ->latest();

        if (!empty($request->status))
            $duels = $duels->where('status', $request->status);

        $duels = $duels->paginate();

        return DuelResource::collection($duels);
    }

    public function getDuelInfo(Duel $duel)
    {
        $duel->load([
            'member', 'opponent',
            'tableType', 'duelType', 'duelLevel', 'store',
        ]);

        return new DuelResource($duel);
    }

    public function sign(Duel $duel)
    {
        if ($duel->status != DuelStatus::Pending)
            return ApiResponseHelper::json([], 400, '该约球已无法报名');

        if ($duel->start_at < now())
            return ApiResponseHelper::json([], 400, '该约球已过期');

        if ($duel->member_id == Auth::id())
            return ApiResponseHelper::json([], 400, '不能报名自己发起的约球');

        $duel->update([
            'opponent_id' => Auth::id(),
            'status' => DuelStatus::PendingReview,
        ]);

        return new DuelResource($duel);
    }
}
